package esb.chapter5.camel.servicemix;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.transform.Source;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;
import org.apache.servicemix.jbi.jaxp.SourceTransformer;
import org.apache.servicemix.jbi.jaxp.StringSource;

public class StreamHandlerComponent extends ComponentSupport implements MessageExchangeListener{
	
	private final static Logger logger = Logger.getLogger(StreamHandlerComponent.class);
	@Resource
	private DeliveryChannel channel;
	private SourceTransformer sourceTransformer = new SourceTransformer();
	
	public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	if (exchange.getStatus() != ExchangeStatus.ACTIVE) return;
    	String message = null;
    	try {
	    	Source contentSource = getInMessage(exchange).getContent();
	    	System.out.println("source type is " + contentSource.getClass().getName());
			message = sourceTransformer.toString(contentSource);
    	} catch(Exception e) {
        	logger.error("error while reading payload", e);
        }
    	NormalizedMessage outMessage = exchange.createMessage();
    	outMessage.setContent(new StringSource(message));
    	exchange.setMessage(outMessage, "out");
		channel.send(exchange);
	}
}
